package org.buptsse.ui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.buptsse.study.HttpDownLoader;
import org.buptsse.study.MyAdapter;
import org.buptsse.ui.PostReplyActivity.GetData;
import org.buptsse.ui.PostReplyActivity.Init;
import org.buptsse.ui.PostReplyActivity.replyButtonListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DocReplyActivity extends ListActivity {

	TextView sizeView=null;
	//ImageView photo=null;
	private Handler dialogHandler = null;
	ProgressDialog myDialog;
	private final int finish = 0;
	private final int end = 1;
	private final int download = 2;
	private static final int DIALOG = 1;  
	private static final int PROGRESSDIALOG = 2;
	private static final int PROGRESS = 3;
	private static final int DOWNLOAD = 4;
	MyAdapter myAdapter;
	HttpResponse response;
	HttpClient client;
	HttpPost post;
	List<NameValuePair> parameter;
	StringBuilder builder;
	BufferedReader reader;
	//Bitmap bitmap = null;
	String path,replyContent,size,docname,time,username,docid,uri,defuri="http://rebook-photo.stor.sinaapp.com/20120320191559.jpg";
	String myName;
	ArrayList<HashMap<String, String>> replylist =new ArrayList<HashMap<String,String>>();
    
   @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

@Override
protected void onPause() {
	// TODO Auto-generated method stub
	super.onPause();
}

@Override
protected void onRestart() {
	// TODO Auto-generated method stub
	super.onRestart();
}

@Override
protected void onStart() {
	// TODO Auto-generated method stub
	super.onStart();
}

@Override
protected void onStop() {
	// TODO Auto-generated method stub
	super.onStop();
}



class Init extends Thread
{
	public void run()
	{
		client=new DefaultHttpClient();
        post=new HttpPost("http://rebook.sinaapp.com/searchphoto.php");
		parameter=new ArrayList<NameValuePair>(); 
    	parameter.add(new BasicNameValuePair("username",username));
    	try {
    		post.setEntity(new UrlEncodedFormEntity(parameter));
			response=client.execute(post);
			reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			builder=new StringBuilder();
			for(String s=reader.readLine();s!=null;s=reader.readLine())
			{
				builder.append(s);
			}
			if(builder.toString()==null)
			{
				//bitmap=getImage(defuri);
			}
			else
			{
				//bitmap=getImage(builder.toString());
			}
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        GetJsonArray();
        if(dialogHandler!=null)dialogHandler.sendEmptyMessage(end);
	}
}
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.doc);
        TextView docnameView=(TextView)findViewById(R.id.posttitle);
        docnameView.setText("大小");
        showDialog(PROGRESS);
        username=this.getIntent().getStringExtra("username");
        docid=this.getIntent().getStringExtra("docid");
        docname=this.getIntent().getStringExtra("docname");
        time=this.getIntent().getStringExtra("time");
        size=this.getIntent().getStringExtra("size");
        path=this.getIntent().getStringExtra("path");
        //photo=(ImageView)findViewById(R.id.photo);
        TextView titleView=(TextView)findViewById(R.id.posttitle);
        TextView userView=(TextView)findViewById(R.id.username);
        TextView timeView=(TextView)findViewById(R.id.time);
        sizeView=(TextView)findViewById(R.id.replynum);
        titleView.setText(docname);
        userView.setText(username);
        timeView.setText(time);
        sizeView.setText(size);
        dialogHandler = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case finish:
					myAdapter=new MyAdapter(DocReplyActivity.this,replylist);
			    	setListAdapter(myAdapter);
					dismissDialog(PROGRESSDIALOG);
					break;
				case end:
					//photo.setImageBitmap(bitmap);
					myAdapter=new MyAdapter(DocReplyActivity.this,replylist);
			    	setListAdapter(myAdapter);
					dismissDialog(PROGRESS);
					break;
				case download:
					dismissDialog(DOWNLOAD);
					break;
				}
			}
		};
    }
    
    private void postReply()
    {
    	CloudLearningApp cloudApp=(CloudLearningApp)getApplication();
    	myName=cloudApp.getUsername();
    	HttpClient client=new DefaultHttpClient();
    	StringBuilder builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	HttpPost post=new HttpPost("http://rebook.sinaapp.com/docreplypublish.php");
    	List<NameValuePair> parameter=new ArrayList<NameValuePair>();
    	parameter.add(new BasicNameValuePair("docid",docid));
    	parameter.add(new BasicNameValuePair("username",myName));
    	parameter.add(new BasicNameValuePair("content",replyContent));
    	
    	try {
			post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
			HttpResponse response=client.execute(post);
			//BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			//for()
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add(0, 1, 1, "回复");
        menu.add(0, 2, 2, "下载");
        menu.add(0, 3, 3, "阅读");
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if(item.getItemId() == 1){
    	showDialog(DIALOG);
    }
    else if(item.getItemId() == 2){
    	showDialog(DOWNLOAD);
    } 
    else if(item.getItemId()==3)
    {
    }
    return true;
}
    
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==1){  
        return this.buildDialog(DocReplyActivity.this);  
        }else if(id==2){
        	return this.buildProgressDialog(DocReplyActivity.this);
        }  
        else if(id==3)
        {
        	return this.buildProgress(DocReplyActivity.this);
        }
        else if(id==4)
        {
        	return this.buildDownload(DocReplyActivity.this);
        	
        }
        else
        {
        	return null;
        }
    }  
    
    protected void Afterpost() {
	    dismissDialog(DIALOG);
    	showDialog(PROGRESSDIALOG);
    }
 
    class DownThread extends Thread
    {
    	public void run()
    	{
    		HttpDownLoader dl=new HttpDownLoader();
    	    dl.downFile(path,"study/",docname);
    	    if(dialogHandler!=null)dialogHandler.sendEmptyMessage(download);
    	}
    }
    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(id, dialog);  
        switch (id) {
		case PROGRESSDIALOG:
			new GetData().start();
			break;
		case PROGRESS:
			new Init().start();
			break;
		case DOWNLOAD:
			new DownThread().start();
			break;
		}
    }  
    
    private Dialog buildDownload(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("下载中……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;
    }
    
    private Dialog buildProgress(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("加载中……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;
    }
    
    private Dialog buildProgressDialog(Context context)
    {
    	Dialog resultDialog = new ProgressDialog(this);;
    	resultDialog.setTitle("正在发帖……");
    	((ProgressDialog) resultDialog).setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	return resultDialog;

    }
      
    private Dialog buildDialog(Context context){  
    	LayoutInflater inflater = (LayoutInflater) DocReplyActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.edittext, null);
        AlertDialog.Builder builder =   new AlertDialog.Builder(context);
        builder.setTitle("回帖").setView(view);
        builder.setMessage("请输入回复内容");  
        builder.setPositiveButton("回复",new DialogInterface.OnClickListener() {  
              
            @Override 
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
            	EditText replyText=(EditText)view.findViewById(R.id.edittext);
            	replyContent=replyText.getText().toString(); 
                if(replyContent.equals(""))
                {
                	Toast.makeText(DocReplyActivity.this, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                }
                else
                {
                	replyText.setText(null);
                	Afterpost();
                	
                }
            }  
        });  
        
        builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {  
            
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
            	EditText replyText=(EditText)view.findViewById(R.id.edittext);
            	replyText.setText(null);
                // TODO Auto-generated method stub  
            	dialog.dismiss();
            }  
        });
        return builder.create();  
    }  
    
    
   public static Bitmap getImage(String Url) throws Exception {
		try {
			URL url = new URL(Url);
			String responseCode = url.openConnection().getHeaderField(0);
			if (responseCode.indexOf("200") < 0)
				throw new Exception("失败" + responseCode);
			return BitmapFactory.decodeStream(url.openStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new Exception(e.getMessage());
		}
	}
   
   class GetData extends Thread
   {
	   public void run()
	   {
		   postReply();
		   GetJsonArray();
		   if(dialogHandler!=null)dialogHandler.sendEmptyMessage(finish);
	   }
   }
   
   private JSONArray GetJsonArray()
    {
    	client=new DefaultHttpClient();
    	builder=new StringBuilder();
    	JSONArray jsonarray=null;
    	post=new HttpPost("http://rebook.sinaapp.com/docreply.php");
    	parameter=new ArrayList<NameValuePair>(); 
    	parameter.add(new BasicNameValuePair("docid",docid));
    	try {
			post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {
			
			e1.printStackTrace();
		}
    	try {
			response=client.execute(post);
			reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			builder=new StringBuilder();
			for(String s=reader.readLine();s!=null;s=reader.readLine())
			{
				builder.append(s);
			}
			if(builder.toString()==null)
			{
			
			}
			else
			{
				jsonarray=new JSONArray(builder.toString());
				JSONObject jsonObject;
				if(jsonarray!=null)
				{
					replylist.clear();
					for(int i=0;i<jsonarray.length();i++)
					{
						jsonObject=jsonarray.getJSONObject(i);
						HashMap<String,String> map=new HashMap<String,String>();
						post=new HttpPost("http://rebook.sinaapp.com/searchphoto.php");
						parameter=new ArrayList<NameValuePair>(); 
				    	parameter.add(new BasicNameValuePair("username",jsonObject.getString("username")));
				    	try {
							post.setEntity(new UrlEncodedFormEntity(parameter,HTTP.UTF_8));
						} catch (UnsupportedEncodingException e1) {
							
							e1.printStackTrace();
						}
				    	response=client.execute(post);
				    	reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				    	builder=new StringBuilder();
				    	for(String s=reader.readLine();s!=null;s=reader.readLine())
						{
							builder.append(s);
						}
						map.put("username",jsonObject.getString("username"));
						map.put("time",jsonObject.getString("time"));
						map.put("content",jsonObject.getString("content"));
						map.put("photo",builder.toString());
						replylist.add(map);
					}
				}
			}
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			System.out.println("client---->"+e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("IO---->"+e.toString());
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("json---->"+e.toString());
			e.printStackTrace();
		}
		return jsonarray;
    }
}
